package org.sardine.beans;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 
 * 用以记录 bean 实例的所有属性信息及给属性的setter方法信息
 * 
 * @author BearBear
 *
 */
public class BeanObjectIntrospection {
	
	private final BeanInfo beanInfo;
	private final Map<String,BeanObjectPropertyDescriptor> propertyDescriptors;
	
	public BeanObjectIntrospection(Class beanClass,Class stopClass){
		
		try {
			
			this.beanInfo = Introspector.getBeanInfo(beanClass,stopClass);
			
			this.propertyDescriptors = new HashMap<String,BeanObjectPropertyDescriptor>();
			PropertyDescriptor[] pds= this.beanInfo.getPropertyDescriptors();
			for (int i = 0; i < pds.length; i++){
				
				PropertyDescriptor pd = pds[i];
				String fieldName = pd.getName();
				Method setterMethod = pd.getWriteMethod();
				//某些属性的setter为null,例如class属性，不进行记录
				if(setterMethod != null){
					BeanObjectPropertyDescriptor bpd = new BeanObjectPropertyDescriptor(beanClass,fieldName,setterMethod);
					this.propertyDescriptors.put(fieldName, bpd);
				}
				
			}
			
			
		} catch (IntrospectionException e) {
			throw new BeanObjectIntrospectionException("无法从"+beanClass.getName()+"对象获取BeanInfo",e);
		}
		
	}

	public Map<String, BeanObjectPropertyDescriptor> getPropertyDescriptors() {
		return propertyDescriptors;
	}
	
	

}
